package com.nsoft.html5npub.business;

import java.util.Map;

import android.content.Context;

import com.nsoft.html5npub.data.DatabaseHandler;
import com.nsoft.html5npub.objects.BookItem;
import com.nsoft.html5npub.objects.BookmarkItem;

/**
 * this class support interacting with database by 
 * static functions<br>
 * 
 * @author minhld
 *
 */
public class dbengine {
	private static DatabaseHandler dbHandler=null;
	public static Map<String,BookItem> dbBookList=null;
	
	/**
	 * <b>startDb</b> has to be called at first<br>
	 * this function should be located at <b>onCreate()</b>
	 * of an activity
	 * 
	 * @param c
	 */
	public static void startDb(Context c){
		dbHandler=new DatabaseHandler(c);
	}
	
	public static void getDownloadedBookList(){
		if (dbHandler!=null)
			dbBookList=dbHandler.getBookMap();
	}
	
	public static boolean checkBookDownloaded(String bookId){
		if (dbBookList==null||dbBookList.size()==0)
			return false;
		return dbBookList.containsKey(bookId);
	}

	public static boolean updateBook(BookItem book){
		if (dbBookList.containsKey(book)){
			return dbHandler.updateBook(book);
		}else{
			return dbHandler.addBook(book);
		}
	}
	
	public static boolean deleteBook(String bookId){
		return dbHandler.deleteBook(bookId);
	}
	
	public static boolean addBookmark(BookmarkItem bmItem){
		return dbHandler.addBookmark(bmItem);
	}
	
	/**
	 * delete a bookmark<br>
	 * contentId (or bookId) and pageId must be specified
	 * 
	 * @param bmItem
	 * @return
	 */
	public static boolean deleteBookmark(BookmarkItem bmItem){
		return dbHandler.deleteBookmark(bmItem);
	}
	
	/**
	 * delete all bookmarks related to a book, which indicated
	 * by bookId (or contentId)
	 * 
	 * @param bookId
	 * @return
	 */
	public static boolean deleteBookmarksOfBook(String bookId){
		return dbHandler.deleteBookmarkOfBook(bookId);
	}
	
	/**
	public static Map<BookCoord,BookmarkItem> getBookmarkMap(
										String bookId){
		return dbHandler.getBookMarkMap(bookId);
	}
	*/
	public static Map<String,BookmarkItem> getBookmarkMap(
										String bookId){
		return dbHandler.getBookMarkMap(bookId);
	}
	
	/**
	 * check if the bookmark exists in database<br>
	 * contentId (or bookId) and pageId must be specified
	 * 
	 * @param bmItem
	 * @return
	 */
	public static boolean isBookmarkExist(
						BookmarkItem bmItem){
		return dbHandler.isBookmarkExist(bmItem);
	}
	
	/**
	 * check if the bookmark exists in database<br>
	 * contentId (or bookId), page index X and Y are all
	 * required
	 * 
	 * @param bookId
	 * @param pageX
	 * @param pageY
	 * @return
	 */
	public static boolean isBookmarkExist(
			String bookId,int pageX,int pageY){
		return dbHandler.isBookmarkExist(
						bookId,pageX,pageY);
	}
}
